package com.yyf.springboot2.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yyf.springboot2.VoEntity.GoodsJsonEntity;
import com.yyf.springboot2.common.AuthToken;
import com.yyf.springboot2.common.IdWorker;
import com.yyf.springboot2.common.ResultBean;
import com.yyf.springboot2.entity.TGoods;
import com.yyf.springboot2.entity.TOrder;
import com.yyf.springboot2.entity.TOrderlist;
import com.yyf.springboot2.entity.TUser;
import com.yyf.springboot2.service.TGoodsService;
import com.yyf.springboot2.service.TOrderService;
import com.yyf.springboot2.service.TOrderlistService;
import com.yyf.springboot2.service.TUserService;
import org.apache.velocity.runtime.directive.Foreach;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yyf
 * @since 2019-05-29
 */
@Controller
@RequestMapping("/tOrder")
public class TOrderController {
    @Resource
    private TUserService userService;
    @Resource
    private TGoodsService goodsService;
    @Resource
    private TOrderService orderService;
    @Resource
    private TOrderlistService orderlistService;

    @PostMapping("/create")
    @ResponseBody
    public ResultBean createOrder(@RequestParam(value = "token") String token,
                                  @RequestParam(value = "goodsJsonStr")String goodsJsonStr,
                                  @RequestParam(value = "remark") String remark
                                  ){
        // token解密,获取用户的id
        Integer uid = null;
        TUser loginUser = null;
        try {
            String  userId = AuthToken.decrypt(token,1);
             uid = Integer.valueOf(userId);
            loginUser= userService.getUserInfoById(uid);
            if(loginUser == null){
                return  ResultBean.build(404,"用户不存在",null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        //待处理
            //TODO:检查传递的下单信息,商品是否存在,库存是否充足,是否是挂卖状态.
            List<GoodsJsonEntity> obs = JSONObject.parseArray(goodsJsonStr,GoodsJsonEntity.class);

            //根据token和goodsJsonStr 及remark创建订单少时诵诗书+
            //生成orderList 和
            List<TOrderlist> orderlists = new ArrayList <>();
             BigDecimal bigDecimal = new BigDecimal("0.00");

            for (int i = 0; i <obs.size() ; i++) {
                Integer goodsId = obs.get(i).getGoodsId();
                Integer goodsNum = obs.get(i).getNumber();
                //根据商品id查询商品信息， 包括库存，价格，是否上架
                TGoods goods = goodsService.getById(goodsId);
                if(goods.getStat() != 0 || goods.getInventory() < goodsNum){
                    return ResultBean.build(104,"商品库存不足或商品已下架",null);
                }
                TOrderlist orderlist = new TOrderlist();
                orderlist.setTotalPrice(goods.getHyPrice() * goodsNum);
                orderlist.setPrice(goods.getHyPrice());
                orderlist.setNum(goodsNum);
                orderlist.setGoodsName(goods.getGoodsName());
                orderlist.setGoodsId(goodsId);
                orderlists.add(orderlist);
                bigDecimal.add(BigDecimal.valueOf(goods.getHyPrice() * goodsNum));

            }
            TOrder order = new TOrder();
            order.setTotalPrice(bigDecimal.doubleValue());
        order.setAddress("四川省成都市武侯区一环路西一段:-D12号");
        order.setCreateTime(new Date());
        order.setLogistics(remark);
        order.setStat(0);
        order.setTotalScore(bigDecimal.doubleValue());
        order.setName("123456 ");
        order.setPhone("13760157412");
        //生成流水号
        order.setSerialNumber(IdWorker.createId());
        //生成orderId
        order.setOrderId(IdWorker.createOrderId());
        order.setPayType(1);//支付方式，未定
        order.setType(1);//订单类型,未定
        order.setUserId(uid);
        order.setId(null);
        order.setUserType(loginUser.getType());//会员类型
        order.setWords(" sa");
        Integer result =  orderService.saveOrder(order,orderlists);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("order",order);
        JSONObject jsonObject = new JSONObject(map);

          if(result > 0){
              return ResultBean.build(200,"保存订单成功",jsonObject);
          }
          return  ResultBean.build(100,"保存错误",null);

    }



    @PostMapping("/list")
    @ResponseBody
    public  ResultBean orderList(
            @RequestParam(value = "token",required = false) String token,
                                 @RequestParam(value = "status") Integer status,
                                 @RequestParam(value = "hasRefund")boolean hasRefund,
                                 @RequestParam(value = "page") Integer page,
                                 @RequestParam(value = "pageSize")Integer pageSize
    ){
        Integer userId = 1;
//        try {
//         String   uId = AuthToken.decrypt(token,1);
//         userId = Integer.valueOf(uId);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        if(userId == nul。l){
//            return  ResultBean.build(104,"token验证失败，请重新获取token",null);
//        }
      //根据用户id和状态，以及hasRefund ，获取不同类型的订单,需要分页,按条数查询,每次十条
        List<TOrder> userOrders = orderService.getListByTypeAdUser(userId,status,page,pageSize);
        for (TOrder userOrder : userOrders) {
            if(userOrder.getStat() == 0){
                userOrder.setOrderName("未付款订单");
                userOrder.setStatName("未付款");
            }
            else if(userOrder.getStat() == 1){
                userOrder.setOrderName("待发货订单");
                userOrder.setStatName("已付款");
            }
            else if(userOrder.getStat() == 2){
                userOrder.setOrderName("已发货订单");
                userOrder.setStatName("已发货");
            }
            else if(userOrder.getStat() == 3){
                userOrder.setOrderName("待评价订单");
                userOrder.setStatName("待评价");
            }
            else if(userOrder.getStat() == 4){
                userOrder.setOrderName("已完成订单");
                userOrder.setStatName("已完成");
            }
            userOrder.setOrderlists(orderlistService.getListByOrderId(userOrder.getId()));

            List<TOrderlist> ors = orderlistService.getListByOrderId(userOrder.getId());
            userOrder.setNum(ors.size());

            for (TOrderlist ol : ors) {
                //设置每个订单的图片。价格标题。数量
                TGoods goods = goodsService.getgoodsDetails(ol.getGoodsId());
                ol.setImage(goods.getImage());
            }

        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userOrders",userOrders);
        JSONObject jsonObject = new JSONObject(map);
        return  ResultBean.build(200,"访问成功",jsonObject);
    }

    @GetMapping("/detail")
    @ResponseBody
    public  ResultBean orderDetail(@RequestParam(value = "token") String token,@RequestParam(value = "id") Integer orderId){
        //获取订单信息
        Integer userId = 1;
//        try {
//         String   uId = AuthToken.decrypt(token,1);
//         userId = Integer.valueOf(uId);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        if(userId == null){
//            return  ResultBean.build(401,"token验证失败，请重新获取token",null);
//        }

        if(orderId == null || userId == null){
            return  ResultBean.build(401,"订单或用户不存在",null);
        }
        TUser user = userService.getUserAmount(userId);
        if (user == null){
            return  ResultBean.build(104,"用户不存在",null);
        }
        TOrder order = orderService.getById(orderId);
        List<TOrderlist> ors = orderlistService.getListByOrderId(orderId);

        for (TOrderlist ol : ors) {
            //设置每个订单的图片。价格标题。数量
            TGoods goods = goodsService.getgoodsDetails(ol.getGoodsId());
            ol.setImage(goods.getImage());
        }
        order.setOrderlists(ors);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("order",order);
        JSONObject jsonObject = new JSONObject(map);
        return  ResultBean.build(200,"访问成功",jsonObject);
    }


    @PostMapping("/pay")
    @ResponseBody
    public ResultBean pay(@RequestParam(value = "orderId") Integer orderId,@RequestParam(value = "token")String token){
        Integer userId = 1;
//        try {
//         String   uId = AuthToken.decrypt(token,1);
//         userId = Integer.valueOf(uId);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        if(userId == null){
//            return  ResultBean.build(401,"token验证失败，请重新获取token",null);
//        }

        if(orderId == null || userId == null){
            return  ResultBean.build(401,"订单或用户不存在",null);
        }
        TUser user = userService.getUserAmount(userId);

        TOrder order = orderService.getById(orderId);
        if (user == null ||  order == null){
            return  ResultBean.build(401,"用户或订单不存在",null);
        }
        if(user.getMoneyMy() < order.getTotalPrice()){
            return  ResultBean.build(104,"用户余额不足",null);
        }
        //去扣扣,改订单状态
      Integer result =   orderService.payOrder(userId,orderId);
        if(result > 0 ){
            return  ResultBean.build(200,"支付成功",null);
        }else{
            return  ResultBean.build(104,"支付失败",null);
        }



    }
	
}
